package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.UserFollowMapper;
import com.heima.user.service.ApUserService;
import com.heima.user.service.UserFollowService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserFollowServiceImpl extends ServiceImpl<UserFollowMapper, ApUserFollow> implements UserFollowService {
    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //cacheService.lRemove(dto.getArticleId() + "follow", 0, 0 + "");
        if (AppThreadLocalUtil.getUser() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (dto.getOperation() == 0) {
                ApUserFollow userFollow = new ApUserFollow();
                userFollow.setFollowId(dto.getAuthorId());
                userFollow.setUserId(AppThreadLocalUtil.getUser().getId());
                userFollow.setCreatedTime(new Date());
                save(userFollow);
                cacheService.lLeftPush(dto.getArticleId() + "follow", dto.getOperation() + "");
        } else {
            ApUserFollow one = getOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getFollowId, dto.getAuthorId()));
            if (one != null) {
                removeById(one);
                cacheService.lRightPop(dto.getArticleId() + "follow");
            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }
}
